package cn.xchats.rpc.server;


import cn.xchats.rpc.common.core.CacheBeanMethod;
import cn.xchats.rpc.common.core.NettyDecoder;
import cn.xchats.rpc.common.dto.RequestDto;
import cn.xchats.rpc.common.dto.ResponseDto;
import cn.xchats.rpc.common.type.NettyType;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/*
 *
 *@author teddy
 *@date 2018/6/26
 */
public class TcpServerHander extends ChannelInboundHandlerAdapter {

    private static final ResponseDto heartbeatResponse=new ResponseDto();

    public TcpServerHander(){
        heartbeatResponse.setBody(NettyType.ALL_IDLE_MSG);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) { // 读取数据
        //获取请求值 (相当于request)
        RequestDto request;
        try {
            request = (RequestDto)msg;
        } catch (Exception e) {
            throw new NullPointerException("server > > > > 解码错误");
        }

        CacheBeanMethod cacheBeanMethod = CacheBeanMethod.getInstance();
        //执行方法
        ResponseDto response = cacheBeanMethod.process(request);

        ctx.channel().writeAndFlush(response);

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // 异常
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { //超时
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            IdleState state = event.state();
            if (state == IdleState.READER_IDLE) {
                System.out.println("读空闲  >>>> ");
            } else if (state == IdleState.WRITER_IDLE) {
                System.out.println("写空闲  >>>> ");
            } else if (state == IdleState.ALL_IDLE) {
                System.out.println("读写空闲");
                ctx.channel().writeAndFlush(heartbeatResponse);
            }
        }
    }
}
